<?php

declare(strict_types=1);

namespace App\Job;

use App\Models\CommodityActivityPushMaterial;
use App\Models\WechatUser;
use App\Service\WechatFactory;
use Carbon\Carbon;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Text;
use Hyperf\AsyncQueue\Job;
use Hyperf\Database\Model\Collection;

class PushActivityMaterialJob extends Job
{
    protected $material;

    protected $openId;

    public function __construct($material, $openId = '')
    {
        $this->material = $material;
        $this->openId = $openId;
    }

    public function handle()
    {
        $app = (new WechatFactory())->officialAccount(false);

        // 如果是指定用户
        if ($this->openId !== '') {
            if (in_array((int) $this->material['type'], [CommodityActivityPushMaterial::TYPE_TEXT, CommodityActivityPushMaterial::TYPE_VIDEO])) {
                $app->customer_service->message(new Text($this->material['content']))->to($this->openId)->send();
            } elseif ((int) $this->material['type'] === CommodityActivityPushMaterial::TYPE_PICTURE) {
                $app->customer_service->message(new Image($this->material['attachments'][0]['wx_media_id']))->to($this->openId)->send();
            }

            return;
        }

        $nowSub48Hours = Carbon::now()->subHours(48);
        WechatUser::query()
            ->select(['openid'])
            ->where('receive_last_message', '>', $nowSub48Hours) // 过滤掉 超过 48 小时没有互动的
            ->chunk(2000, function (Collection $userList) use ($app) {
                $userList->each(function ($user) use ($app) {
                    go(function () use ($user, $app) {
                        if (in_array((int) $this->material['type'], [CommodityActivityPushMaterial::TYPE_TEXT, CommodityActivityPushMaterial::TYPE_VIDEO])) {
                            $app->customer_service->message(new Text($this->material['content']))->to($user['openid'])->send();
                        } elseif ((int) $this->material['type'] === CommodityActivityPushMaterial::TYPE_PICTURE) {
                            $app->customer_service->message(new Image($this->material['attachments'][0]['wx_media_id']))->to($user['openid'])->send();
                        }
                    });
                });
            });
    }
}
